const { pool, data_url } = require('../database.js');

// 获取帖子列表
const getForumPosts = async (request, response) => {
  try {
    const { page = 1, page_size = 10, search = '' } = request.body;
    const offset = (page - 1) * page_size;
    const user_id = request.query.user_id ? parseInt(request.query.user_id) : 0;

    // 修改 SQL 语句，确保参数数量匹配
    const sql = `
      SELECT 
        p.*,
        u.author_name,
        u.avatar_url,
        EXISTS (
          SELECT 1 
          FROM forum_post_likes l 
          WHERE l.post_id = p.post_id 
          AND l.user_id = ${user_id}
        ) as is_liked
      FROM forum_posts p
      LEFT JOIN users u ON p.user_id = u.user_id
      WHERE p.status = 1
      ${search ? 'AND (p.title LIKE ? OR p.content LIKE ?)' : ''}
      ORDER BY p.create_time DESC
      LIMIT ${parseInt(page_size)} OFFSET ${parseInt(offset)}
    `;

    const countSql = `
      SELECT COUNT(*) as total
      FROM forum_posts
      WHERE status = 1
      ${search ? 'AND (title LIKE ? OR content LIKE ?)' : ''}
    `;

    // 构建参数数组
    const sqlParams = [];
    if (search) {
      sqlParams.push(`%${search}%`, `%${search}%`);
    }

    const countParams = search ? [`%${search}%`, `%${search}%`] : [];

    const [posts] = await pool.execute(sql, sqlParams);
    const [countResult] = await pool.execute(countSql, countParams);

    response.json({
      code: "200",
      msg: "success",
      data: {
        list: posts.map(post => ({
          ...post,
          avatar_url: post.avatar_url ? data_url + post.avatar_url : null,
          create_time: post.create_time.toLocaleString()
        })),
        pagination: {
          current: parseInt(page),
          page_size: parseInt(page_size),
          total: countResult[0].total
        }
      }
    });
  } catch (error) {
    console.error('获取帖子列表失败:', error);
    response.json({
      code: "500",
      msg: "服务器错误",
      error: error.message
    });
  }
};

// 发布帖子
const createPost = async (request, response) => {
  try {
    const user_id = request.query.user_id;
    const { title, content } = request.body;

    const sql = `
      INSERT INTO forum_posts (user_id, title, content)
      VALUES (?, ?, ?)
    `;

    const [result] = await pool.execute(sql, [user_id, title, content]);

    response.json({
      code: "200",
      msg: "发布成功",
      data: {
        post_id: result.insertId
      }
    });
  } catch (error) {
    console.error('发布帖子失败:', error);
    response.json({
      code: "500",
      msg: "服务器错误",
      error: error.message
    });
  }
};

// 获取帖子评论
const getPostComments = async (request, response) => {
  try {
    const { post_id } = request.body;

    const sql = `
      SELECT 
        c.*,
        u.author_name,
        u.avatar_url
      FROM forum_comments c
      LEFT JOIN users u ON c.user_id = u.user_id
      WHERE c.post_id = ?
      AND c.status = 1
      ORDER BY c.create_time DESC
    `;

    const [comments] = await pool.execute(sql, [post_id]);

    response.json({
      code: "200",
      msg: "success",
      data: comments.map(comment => ({
        ...comment,
        avatar_url: comment.avatar_url ? data_url + comment.avatar_url : null,
        create_time: comment.create_time.toLocaleString()
      }))
    });
  } catch (error) {
    console.error('获取评论失败:', error);
    response.json({
      code: "500",
      msg: "服务器错误",
      error: error.message
    });
  }
};

// 发表评论
const createComment = async (request, response) => {
  try {
    const { post_id, content } = request.body;
    const user_id = request.query.user_id;

    const sql = `
      INSERT INTO forum_comments (post_id, user_id, content)
      VALUES (?, ?, ?)
    `;

    const [result] = await pool.execute(sql, [post_id, user_id, content]);

    // 更新帖子评论数
    await pool.execute(
      'UPDATE forum_posts SET comments_count = comments_count + 1 WHERE post_id = ?',
      [post_id]
    );

    response.json({
      code: "200",
      msg: "评论成功",
      data: {
        comment_id: result.insertId
      }
    });
  } catch (error) {
    console.error('发表评论失败:', error);
    response.json({
      code: "500",
      msg: "服务器错误",
      error: error.message
    });
  }
};

// 点赞/取消点赞帖子
const togglePostLike = async (request, response) => {
  try {
    const { post_id } = request.body;
    const user_id = request.query.user_id;

    const [existingLike] = await pool.execute(
      'SELECT like_id FROM forum_post_likes WHERE post_id = ? AND user_id = ?',
      [post_id, user_id]
    );

    if (existingLike.length > 0) {
      // 取消点赞
      await pool.execute(
        'DELETE FROM forum_post_likes WHERE post_id = ? AND user_id = ?',
        [post_id, user_id]
      );
      await pool.execute(
        'UPDATE forum_posts SET likes = likes - 1 WHERE post_id = ?',
        [post_id]
      );
    } else {
      // 添加点赞
      await pool.execute(
        'INSERT INTO forum_post_likes (post_id, user_id) VALUES (?, ?)',
        [post_id, user_id]
      );
      await pool.execute(
        'UPDATE forum_posts SET likes = likes + 1 WHERE post_id = ?',
        [post_id]
      );
    }

    response.json({
      code: "200",
      msg: existingLike.length > 0 ? "取消点赞成功" : "点赞成功"
    });
  } catch (error) {
    console.error('点赞操作失败:', error);
    response.json({
      code: "500",
      msg: "服务器错误",
      error: error.message
    });
  }
};

module.exports = {
  getForumPosts,
  createPost,
  getPostComments,
  createComment,
  togglePostLike
};

// --评论点赞表
// CREATE TABLE`forum_comment_likes`(
//   `like_id` int NOT NULL AUTO_INCREMENT,
//   `comment_id` int NOT NULL COMMENT '评论ID',
//   `user_id` int NOT NULL COMMENT '点赞用户ID',
//   `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '点赞时间',
//   PRIMARY KEY(`like_id`),
//   UNIQUE KEY`unique_comment_user_like`(`comment_id`, `user_id`) COMMENT '确保用户对同一评论只能点赞一次',
//   CONSTRAINT`fk_comment_like_comment` FOREIGN KEY(`comment_id`) REFERENCES`forum_comments`(`comment_id`) ON DELETE CASCADE,
//   CONSTRAINT`fk_comment_like_user` FOREIGN KEY(`user_id`) REFERENCES`users`(`user_id`) ON DELETE CASCADE
// ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '评论点赞表';